package com.atguigu.gulimall.auth.demos.web.Controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRsepVo;
import com.atguigu.gulimall.auth.demos.feign.MemberFeignService;
import com.atguigu.gulimall.auth.demos.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.demos.utils.CodeUtils;
import com.atguigu.gulimall.auth.demos.vo.UserLoginVo;
import com.atguigu.gulimall.auth.demos.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private View error;
    @Autowired
    MemberFeignService memberFeignService;
    @ResponseBody
    @GetMapping("sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(s)) {
            Long s1 = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis() - s1 < 60 * 1000) {
                //发送频率太高
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        CodeUtils codeUtils = new CodeUtils();
        String code = codeUtils.getCode(6) + "_" + System.currentTimeMillis();
        String codec = code.split("_")[0];
        thirdPartyFeignService.SendCode(phone, codec);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        return R.ok();
    }

    @PostMapping("/regist")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors", errors);

            return "redirect:http://auth.gulimall.com.reg.html";
        }
        String code = userRegisterVo.getCode();
        String rediscode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());

        if (!StringUtils.isEmpty(rediscode)) {
            if (rediscode.split("_")[0].equals(code)) {
                //验证码正确就删除
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
                //
                R register = memberFeignService.register(userRegisterVo);
               if (register.getCode()==0){
                   return "redirect:http://auth.gulimall.com.login.html";
               }
               else {
                   Map<String, String> errors = new HashMap<>();
                   errors.put("msg",register.getData("msg",new TypeReference<String>(){}));
                   redirectAttributes.addFlashAttribute("errors", errors);
                   return "redirect:http://auth.gulimall.com.reg.html";
               }

            }
            else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com.reg.html";
            }
        }
        else
        {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com.reg.html";
        }


    }
    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession httpSession){
        R r = memberFeignService.login(userLoginVo);
       if (r.getCode()==0){
           MemberRsepVo data = r.getData("data", new TypeReference<MemberRsepVo>() {
           });
           //登录成功
           httpSession.setAttribute(AuthServerConstant.LOGIN_USER,data);
           return "redirect:http://gulimall.com";
       }else {
           Map<String, String> errors = new HashMap<>();
           errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
           redirectAttributes.addFlashAttribute("errors",errors);
           return "redirect:http://auth.gulimall.com/login.html";
       }

    }
    @GetMapping("/login")
    public String loginPage(HttpSession session){
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser!=null){
            return "redirect:http://gulimall.com";
        }else {
            return "login";
        }
    }
    @ResponseBody
    @GetMapping("/test")
    public String test(HttpSession session){
        session.setAttribute("login","123");
        return session.getAttribute("login").toString();
    }
}
